import React, { useEffect } from 'react';
import Swiper from 'swiper/js/swiper'
import 'swiper/css/swiper.min.css'


export default function Carousel(props) {
    const { width = "100%", height = "100px", className = "", autoPlay = true } = props
    useEffect(() => {
        let mySwiper = new Swiper('.carousel-main', {
            autoplay: autoPlay
                ? {
                    disableOnInteraction: false,
                    delay: 2000,
                }
                : false,
            // loop: true,
            speed: 500,
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            observer: true,
            on: {
                resize: function () {
                    mySwiper.update();
                },
            },
        });

        //悬停时暂停，离开时继续
        const container = document.querySelector('.carousel-main'); // 容器
        const stop = () => mySwiper.autoplay && mySwiper.autoplay.stop();
        const start = () => mySwiper.autoplay && mySwiper.autoplay.start();

        if (container && autoPlay) {
            container.addEventListener('mouseenter', stop);
            container.addEventListener('mouseleave', start);
        }
        return () => {
            if (container && autoPlay) {
                container.removeEventListener('mouseenter', stop);
                container.removeEventListener('mouseleave', start);
            }
            mySwiper.destroy();
        };
    }, [autoPlay]);
    return (
        <div className={`swiper-container carousel-main ${className}`} style={{ width: width, height: height }}>
            <div className="swiper-wrapper">
                {
                    props.children
                }
            </div>
            <div className="swiper-pagination"></div>
        </div>
    )
}